# -*- coding: utf-8 -*-
"""
Web framework/Tornado Httpclient/test01.py
"""
from tornado import httpclient, simple_httpclient, curl_httpclient
import asyncio
import tornado.web
import sys
import functools


class IndexHandler(tornado.web.RequestHandler):

    async def get(self):
        print("-----------------async_http_client()-------------------------")
        self.async_http_client()
        print("-----------------await_http_client()-------------------------")
        await self.await_http_client()
        print("-----------------simple_http_client()-------------------------")
        self.simple_http_client()
        print("-----------------await_simple_http_client()-------------------------")
        await self.await_simple_http_client()
        print("-----------------curl_http_client()-------------------------")
        self.curl_http_client()
        print("-----------------await_curl_http_client()-------------------------")
        await self.await_curl_http_client()

    def http_client(self):
        """
        tornado.httpclient.HTTPClient()
        同步堵塞HTTP客户端
        :return:
        """
        http_client = httpclient.HTTPClient()
        try:
            response = http_client.fetch("http://www.baidu.com/")
            print("This is response before.")
            print(response)
            print("This is response after.")
        except httpclient.HTTPError as e:
            print(e)
        except Exception as e:
            print(e)

        http_client.close()

    def async_http_client(self):
        """
        tornado.httpclient.AsyncHTTPClient()
        异步非堵塞HTTP客户端
        :return:
        """
        http_client = httpclient.AsyncHTTPClient()
        try:
            response = http_client.fetch("http://www.baidu.com/")
            response.add_done_callback(functools.partial(self.on_response, func_name=sys._getframe().f_code.co_name))
        except httpclient.HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        else:
            print("This is response before.")
            print(response)
            print("This is response after.")

    async def await_http_client(self):
        """
        tornado.httpclient.AsyncHTTPClient()
        同步堵塞HTTP客户端
        :return:
        """
        http_client = httpclient.AsyncHTTPClient()
        try:
            response = await http_client.fetch("http://www.baidu.com/")
        except httpclient.HTTPError as e:
            print(e)
        except Exception as e:
            print(e)
        else:
            print("This is response before.")
            print(response)
            print("This is response after.")

    def simple_http_client(self):
        """
        tornado.simple_httpclient.SimpleAsyncHTTPClient()
        异步非堵塞HTTP客户端
        :return:
        """
        new_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(new_loop)
        http_client = simple_httpclient.SimpleAsyncHTTPClient()
        try:
            response = http_client.fetch("http://www.baidu.com/")
            print("This is response before.")
            print(response)
            print("This is response after.")
        except httpclient.HTTPError as e:
            print(e)
        except Exception as e:
            print(e)

    async def await_simple_http_client(self):
        """
        tornado.simple_httpclient.SimpleAsyncHTTPClient()
        同步堵塞HTTP客户端
        :return:
        """
        http_client = simple_httpclient.SimpleAsyncHTTPClient()
        try:
            response = await http_client.fetch("http://www.baidu.com/")
            print("This is response before.")
            print(response)
            print("This is response after.")
        except httpclient.HTTPError as e:
            print(e)
        except Exception as e:
            print(e)

    def curl_http_client(self):
        """
        tornado.curl_httpclient.CurlAsyncHTTPClient()
        异步非堵塞HTTP客户端
        :return:
        """
        new_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(new_loop)
        http_client = curl_httpclient.CurlAsyncHTTPClient()
        try:
            response = http_client.fetch("http://www.baidu.com/")
            print("This is response before.")
            print(response)
            response.add_done_callback(functools.partial(self.on_response, func_name=sys._getframe().f_code.co_name))
            print("This is response after.")
        except httpclient.HTTPError as e:
            print(e)
        except Exception as e:
            print(e)

    async def await_curl_http_client(self):
        """
        tornado.curl_httpclient.CurlAsyncHTTPClient()
        同步堵塞HTTP客户端
        :return:
        """
        http_client = curl_httpclient.CurlAsyncHTTPClient()
        try:
            response = await http_client.fetch("http://www.baidu.com/")
            print("This is response before.")
            print(response)
            print("This is response after.")
        except httpclient.HTTPError as e:
            print(e)
        except Exception as e:
            print(e)

    def on_response(self, response, func_name):
        print(f'{func_name}: future done: {response}')


async def main():
    app = tornado.web.Application([
        (r'/', IndexHandler)
    ])
    app.listen(8888)
    await asyncio.Event().wait()


if __name__ == '__main__':
    asyncio.run(main())
